package com.ly.canvasdemo

import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.os.Build
import android.view.View
import android.view.ViewConfiguration
import android.widget.ImageView

object NavigationBarInfo {
    private const val TAG = "NavigationBarInfo"

    /**
     * 获取虚拟按键的高度
     */
     fun Context.getNavigationBarHeight(): Int {
        var result = 0
        if (hasNavBar()) {
            val res = resources
            val resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android")
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId)
            }
        }
        return result
    }

    /**
     * 检查是否存在虚拟按键栏
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
     fun Context.hasNavBar(): Boolean {
        val res = resources
        val resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android")
        return if (resourceId != 0) {
            var hasNav = res.getBoolean(resourceId)
            val sNavBarOverride = navBarOverride
            if ("1" == sNavBarOverride) {
                hasNav = false
            } else if ("0" == sNavBarOverride) {
                hasNav = true
            }
            hasNav
        } else {
            !ViewConfiguration.get(this).hasPermanentMenuKey()
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     */
    private val navBarOverride: String?
        private get() {
            var sNavBarOverride: String? = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    val c = Class.forName("android.os.SystemProperties")
                    val m =
                        c.getDeclaredMethod("get", String::class.java)
                    m.isAccessible = true
                    sNavBarOverride = m.invoke(null, "qemu.hw.mainkeys") as String
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return sNavBarOverride
        }


    /**
     * 判断是否是刘海屏
     *
     * @return 是否是刘海屏
     */
    fun hasNotchScreen(activity: Activity): Boolean {
        return (getInt(
            "ro.miui.notch",
            activity
        ) || hasNotchAtHuawei(activity) || hasNotchAtOPPO(
            activity
        )
                || hasNotchAtVivo(activity))
    }

    /**
     * 小米刘海屏判断.
     *
     * @return property ro.miui.notch，值为1时则是 Notch 屏手机
     * SystemProperties.getInt("ro.miui.notch", 0) == 1;
     */
    fun getInt(key: String?, activity: Activity): Boolean {
        var result = 0
        if (isXiaomi) {
            try {
                val classLoader = activity.classLoader
                val SystemProperties =
                    classLoader.loadClass("android.os.SystemProperties")
                //参数类型
                val paramTypes =
                    arrayOfNulls<Class<*>?>(2)
                paramTypes[0] = String::class.java
                paramTypes[1] = Int::class.javaPrimitiveType
                val getInt =
                    SystemProperties.getMethod("getInt", *paramTypes)
                //参数
                val params = arrayOfNulls<Any>(2)
                params[0] = key
                params[1] = 0
                result = getInt.invoke(SystemProperties, *params) as Int
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return result == 1
    }

    /**
     * 华为刘海屏判断
     */
    fun hasNotchAtHuawei(context: Context): Boolean {
        var ret = false
        try {
            val classLoader = context.classLoader
            val HwNotchSizeUtil =
                classLoader.loadClass("com.huawei.android.util.HwNotchSizeUtil")
            val get = HwNotchSizeUtil.getMethod("hasNotchInScreen")
            ret = get.invoke(HwNotchSizeUtil) as Boolean
        } catch (e: ClassNotFoundException) {
            // Logger.e(TAG, "hasNotchAtHuawei ClassNotFoundException");
        } catch (e: NoSuchMethodException) {
            // Logger.e(TAG, "hasNotchAtHuawei NoSuchMethodException");
        } catch (e: Exception) {
            //  Logger.e(TAG, "hasNotchAtHuawei Exception");
        } finally {
            return ret
        }
    }

    /**
     * 华为手机获取刘海尺寸：width、height
     * int[0]值为刘海宽度 int[1]值为刘海高度。
     */
    fun getNotchSize(context: Context): IntArray {
        var ret = intArrayOf(0, 0)
        try {
            val cl = context.classLoader
            val HwNotchSizeUtil =
                cl.loadClass("com.huawei.android.util.HwNotchSizeUtil")
            val get = HwNotchSizeUtil.getMethod("getNotchSize")
            ret = get.invoke(HwNotchSizeUtil) as IntArray
        } catch (e: Exception) {

            // Logger.e(TAG, "getNotchSize Exception");
        } finally {
            return ret
        }
    }

    const val VIVO_NOTCH = 0x00000020 //是否有刘海
    const val VIVO_FILLET = 0x00000008 //是否有圆角

    /**
     * VIVO刘海屏判断
     *
     * @return
     */
    fun hasNotchAtVivo(context: Context): Boolean {
        var ret = false
        try {
            val classLoader = context.classLoader
            val FtFeature = classLoader.loadClass("android.util.FtFeature")
            val method =
                FtFeature.getMethod("isFeatureSupport", Int::class.javaPrimitiveType)
            ret = method.invoke(FtFeature, VIVO_NOTCH) as Boolean
        } catch (e: ClassNotFoundException) {
            //  Logger.e(TAG, "hasNotchAtVivo ClassNotFoundException");
        } catch (e: NoSuchMethodException) {
            //  Logger.e(TAG, "hasNotchAtVivo NoSuchMethodException");
        } catch (e: Exception) {
            //  Logger.e(TAG, "hasNotchAtVivo Exception");
        } finally {
            return ret
        }
    }

    /**
     * OPPO刘海屏判断
     */
    fun hasNotchAtOPPO(context: Context): Boolean {
        return context.packageManager
            .hasSystemFeature("com.oppo.feature.screen.heteromorphism")
    }

    // 是否是小米手机
    val isXiaomi: Boolean
        get() = "Xiaomi" == Build.MANUFACTURER

    val isHuawei: Boolean
        get() = "Huawei" == Build.MANUFACTURER

    val isOppo: Boolean
        get() = "Oppo" == Build.MANUFACTURER

    val isVivo: Boolean
        get() = "Vivo" == Build.MANUFACTURER

    /**
     * 获取小米刘海高度
     *
     * @param activity
     * @return
     */
    fun getXiaomiNotchHight(activity: Activity): Int {
        val resourceId =
            activity.resources.getIdentifier("notch_height", "dimen", "android")
        return if (resourceId > 0) {
            activity.resources.getDimensionPixelSize(resourceId)
        } else 0
    }

    fun getHeight(activity: Activity): Float {
        val dm = activity.resources.displayMetrics
        if (hasNotchScreen(activity)) {
            var notchHight = 0f
            if (isHuawei) {
                notchHight = getNotchSize(activity)[1].toFloat()
            } else if (isXiaomi) {
                notchHight = getXiaomiNotchHight(activity).toFloat()
            } else if (isVivo) {
                notchHight = getXiaomiNotchHight(activity).toFloat()
            } else if (isOppo) {
                notchHight = getXiaomiNotchHight(activity).toFloat()
            }
            return dm.heightPixels + activity.getNavigationBarHeight() - notchHight
        }
        return (dm.heightPixels +  activity.getNavigationBarHeight()).toFloat()
    }
}